package top.frsf.dashboard.utils;

import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;
import top.frsf.dashboard.properties.AuthProperties;

import javax.annotation.Resource;
import java.util.Date;

/**
 * JWT 工具类
 *
 * @author He Kuntao
 * @since 2025/6/3 11:42
 */
@Component
@RequiredArgsConstructor
public class JwtUtil {

    private final AuthProperties authProperties;

    /**
     * 生成 Token
     *
     * @param username 用户名
     * @return Token
     */
    public String generateToken(String username) {
        return Jwts.builder()
                .setSubject(username)
                .setExpiration(new Date(System.currentTimeMillis() + authProperties.getExpire()))
                .signWith(SignatureAlgorithm.HS512, authProperties.getSecret())
                .compact();
    }

    /**
     * 解析 Token
     *
     * @param token 令牌
     * @return username
     */
    public String parseToken(String token) {
        return Jwts.parser()
                .setSigningKey(authProperties.getSecret())
                .parseClaimsJws(token)
                .getBody()
                .getSubject();
    }
}
